<?php


namespace app\common\service\rabbitMQ;


use app\common\enum\MainEnum;
use app\common\exception\LogicException;
use app\common\model\OrderModel;
use app\common\model\UserCouponModel;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;
use think\facade\Db;

class UserCouponExpiredCheck implements RabbitMQBusinessInterface
{
    public static function instance($expire_timestamp = 0): RabbitMQ
    {
        $rabbitMQ = (new RabbitMQ());
        $rabbitMQ->setExchange(__CLASS__ . '_direct_delayed');
        $rabbitMQ->setExchangeType('x-delayed-message');
        $rabbitMQ->setExchangeArguments(
            [
                'x-delayed-type' => AMQPExchangeType::DIRECT,
            ]
        );
        if ($expire_timestamp) {
            $rabbitMQ->setXDelay($expire_timestamp);
        }
        $rabbitMQ->setRoutingKey(__CLASS__);
        $rabbitMQ->setQueue(__CLASS__);
        $rabbitMQ->setConfirmSelectType(
            3,
            [
                static function (AMQPMessage $message) {
                },
                static function (AMQPMessage $message) {
                    throw new LogicException();
                },
                static function ($replyCode, $replyText, $exchange, $routingKey, AMQPMessage $message) {
                },
            ]
        );
        $rabbitMQ->prepare();
        $rabbitMQ->preparePublisher();
        return $rabbitMQ;
    }

    public static function publisher(array $data, int $expire_timestamp = 0)
    {
        $rabbitMQ = self::instance($expire_timestamp);
        $rabbitMQ->publisher(
            [
                [
                    'data' => $data,
                ],
            ]
        );
    }

    public static function consumer($body): bool
    {
        $model = (new UserCouponModel())->where('id', $body['data']['id'])->find();
        if (!$model) {
            return true;
        }
        if ($model->getData('status') !== MainEnum::COUPON_USER_STATUS['待使用']) {
            return false;
        }
        if (strtotime($model->getData('end_time')) > time()) {
            #没过期
            return false;
        }
        #过期了
        $model->status = MainEnum::COUPON_USER_STATUS['已过期'];
        $model->save();
        return true;
    }
}